<!--
 * @FileDescription: 经费认领列表页包括可认领和已认领列表，可根据关键字查询
 * @Author: gushouchen
 * @Date: 2021-10-14
 -->
<template>
  <!-- 经费认领列表 -->
  <div class="ep-wrapper">
    <div class="ep-list-header"
         ref="epListHeader">
      <!-- 导航栏 -->
      <van-nav-bar title="经费认领"
                   left-arrow
                   @click-left="goBack"
                   @click-right="goHome"
                   ref="navbar">
        <template #right>
          <van-icon name="wap-home-o" />
        </template>
      </van-nav-bar>
      <!-- 搜索框 -->
      <ListSearch @doSearch="doSearch" />
    </div>
    <!-- 标签页 -->
    <div class="ep-list-main">
      <van-tabs animated
                sticky
                swipeable
                v-model:active="tabsState.active"
                @change="tabsChange"
                :offset-top="tabsOffsetTop">
        <!-- 可认领列表 -->
        <!-- 对冲号 来款单位 摘要 来款日期 来款金额 可领金额 经费状态 -->
        <van-tab title="可认领">
          <div class="inner-tab"
               ref="tabs">
            <van-pull-refresh v-model="canClaimState.refreshing"
                              @refresh="canClaimState.refresh">
              <van-list v-model:loading="canClaimState.loading"
                        :finished="canClaimState.finished"
                        :finished-text="canClaimState.list.length===0?'无数据':'没有更多了'"
                        @load="loadData">
                <template v-for="item in canClaimState.list"
                          :key="item.id">
                  <ListCard :title="item.incomeUnit"
                            ellipsis="1"
                            rightDescription="去认领"
                            rdColor="#4073F5"
                            linked
                            :to="{name:'cwIncomeClaimPage', params: {'id': item.id}}">
                    <template #content>
                      <div>{{item.note}}</div>
                      <div>{{item.feeValue}} 万元</div>
                      <div>可认领：{{item.notClaimFee}} 万元</div>
                    </template>
                  </ListCard>
                </template>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
        <!-- 已认领列表 -->
        <van-tab title="已认领">
          <div class="inner-tab">
            <van-pull-refresh v-model="claimedState.refreshing"
                              @refresh="claimedState.refresh">
              <van-list v-model:loading="claimedState.loading"
                        :finished="claimedState.finished"
                        :finished-text="claimedState.list.length===0?'无数据':'没有更多了'"
                        @load="loadData">
                <template v-for="item in claimedState.list"
                          :key="item.id">
                  <ListCard :title="item.projectName"
                            rightDescription=""
                            linked
                            :to="{name:'cwIncomeClaimedPage', params: {'id':1212}}">
                    <template #content>
                      <div>
                        <van-icon name="user-o" />
                        {{item.claimerName}}
                      </div>
                      <div>{{item['vproject.unitId']}}</div>
                      <div>{{item.claimDate}}</div>
                    </template>
                  </ListCard>
                </template>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>


<script>
import { Toast } from 'vant'
import { ref, reactive, onMounted, onActivated, nextTick } from 'vue'
import { goHome, goBack, mobileResultCode } from '@/utils/common.js'
import ListCard from '@/components/ListCard.vue'
import ListSearch from '@/components/ListSearch.vue'
import { getCanClaim, getClaimed } from '@/request/api_claim'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

// xda
// export const xda = () => {
//   const a = 1, b = 2
//   return { a, b }
// }
export default {
  components: {
    ListCard, ListSearch
  },
  setup () {
    // const { a } = xda
    // console.log(a)
    // 与 beforeRouteLeave 相同，无法访问 `this`
    // const route = useRoute()
    const tabs = ref()
    const scrollState = reactive({
      canClaim: 0,
      claimed: 0
    })
    // const scroll = ref(0)
    onBeforeRouteLeave((to, from) => {
      console.log(tabs.value)
      scrollState.canClaim = tabs.value.scrollTop
      // scroll =
      // route.meta.keepAlive = false
      // 取消导航并停留在同一页面上
    })

    // 与 beforeRouteLeave 相同，无法访问 `this`
    onBeforeRouteUpdate(async (to, from) => {
      const answer = window.confirm(
        'xxxxx'
      )
      // 取消导航并停留在同一页面上
      if (!answer) return false
    })
    // search状态存储
    const searchKey = ref('')
    // tabs状态存储
    const tabsState = reactive({
      active: 0
    })
    // 计算tabs与顶部距离
    const epListHeader = ref()
    const tabsOffsetTop = ref()
    const computeTabsOffsetTop = () => {
      tabsOffsetTop.value = epListHeader.value.offsetHeight
    }
    onMounted(() => {
      computeTabsOffsetTop()
    })
    // 组件激活时，重新给子组件滚动位置赋值
    onActivated(() => {
      nextTick(() => {
        tabs.value.scrollTop = scrollState.canClaim
      })
    })
    // 更新搜索条件
    const doSearch = (listSearchKey) => {
      searchKey.value = listSearchKey
      canClaimState.finished = false
      requestState.canClaimState.refreshing = true
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      canClaimState.loading = true
      requestState.canClaimState.pageNo = 1
      loadData()
    }
    const requestState = reactive({
      canClaimState: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      claimedState: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      }
    })
    // 数据加载
    const loadData = () => {
      requestStrategy[tabsState.active].apply()
    }
    const requestStrategy = [
      // 可认领
      () => {
        getCanClaim(Object.assign(requestState.canClaimState, { searchKey: searchKey.value })).then(response => {
          if (response.body.code === mobileResultCode.SUCCESS) {
            requestState.canClaimState.total = parseInt(response.body.data.totals)
            requestState.canClaimState.pageNo++
            canClaimState.loading = false
            if (canClaimState.refreshing) {
              canClaimState.refreshing = false
              canClaimState.list = []
            }
            canClaimState.list.push(...response.body.data.item)
            // 判断当前集合中数据，若等于最大值，停止加载更多
            if (canClaimState.list.length >= requestState.canClaimState.total) {
              canClaimState.finished = true
            }
          }
        }
        ).catch(error => {
          debugger
          // 请求不成功
          if (error.code === 'ECONNABORTED') {
            Toast('未能连接到服务器，请检查网络设置')
            canClaimState.refreshing = false
            canClaimState.loading = false
            canClaimState.finished = true
          }
        })
      },
      // 已认领 可优化
      () => {
        debugger
        getClaimed(Object.assign(requestState.claimedState, { searchKey: searchKey.value })).then(response => {
          if (response.body.code === mobileResultCode.SUCCESS) {
            requestState.claimedState.total = parseInt(response.body.data.totals)
            requestState.claimedState.pageNo++
            claimedState.loading = false
            if (claimedState.refreshing) {
              claimedState.refreshing = false
              claimedState.list = []
            }
            claimedState.list.push(...response.body.data.item)
            // 判断当前集合中数据，若等于最大值，停止加载更多
            if (claimedState.list.length >= requestState.claimedState.total) {
              claimedState.finished = true
            }
          }
        }).catch(error => {
          debugger
          // 请求不成功
          if (error.code === 'ECONNABORTED') {
            Toast('未能连接到服务器，请检查网络设置')
            claimedState.refreshing = false
            claimedState.loading = false
            claimedState.finished = true
          }
        })
      }
    ]
    const canClaimState = reactive({
      refreshing: false,
      refresh: () => {
        searchKey.value = ''
        canClaimState.finished = false
        requestState.canClaimState.refreshing = true
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        // canClaimState.loading = true
        requestState.canClaimState.pageNo = 1
        loadData()
      },
      loading: false,
      finished: false,
      list: []
    })
    const claimedState = reactive({
      refreshing: false,
      refresh: () => {
        searchKey.value = ''
        claimedState.finished = false
        requestState.claimedState.refreshing = true
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        claimedState.loading = true
        requestState.claimedState.pageNo = 1
        loadData()
      },
      loading: false,
      finished: false,
      list: []
    })
    const tabsChange = (index, title) => {
      if (index === 0) {
        canClaimState.refresh.apply()
      } else {
        claimedState.refresh.apply()
      }
    }
    return {
      epListHeader,
      goHome,
      goBack,
      tabsOffsetTop,
      ListSearch,
      doSearch,
      tabsState,
      ListCard,
      loadData,
      canClaimState,
      claimedState,
      tabs,
      scrollState,
      tabsChange
    }

  }
}
</script>
<style scoped>
/* 总计 */
.total {
  display: flex;
  align-content: center;
  align-items: center;
  padding-left: 15px;
  height: 33.07px;
  background-color: #f7f7f7;
  font-size: 12px;
  line-height: 16px;
  color: #969799;
}
.van-tabs--line .van-tabs__wrap {
  height: 12px;
}

[class*="van-hairline"]::after {
  position: absolute;
  box-sizing: border-box;
  content: " ";
  pointer-events: none;
  top: -50%;
  right: -50%;
  bottom: -50%;
  left: -50%;
  border: unset;
  transform: scale(0.5);
}
.ep-list-main {
  flex: 1;
  max-height: 100%;
  overflow: scroll;
}
/* 自定义处理插槽内容样式 */
.ep-card-content > div {
  margin-right: 12px;
}

/* 解决多tabs滚动条一起滚动 */
/* 修改tabs变为flex布局，为tabs中的子组件总是填充剩余页面 */
.van-tabs {
  display: flex;
  flex-direction: column;
  height: 100%;
}
::v-deep(.van-tab__pane) {
  height: 100%;
}
::v-deep(.van-tabs__content) {
  flex: 1;
}
/* */
.inner-tab {
  height: 100%;
  overflow: scroll;
}
</style> 